package mlib

import "errors"
import "fmt"

type MusicEntry struct {
	Id string
	Name string 
	Artist string
	Source string
	Type string
}

type MusicManager struct {
	musics []MusicEntry
}

func NewMusicManager() *MusicManager {
	return &MusicManager{ make([]MusicEntry, 0)}
}

func (m *MusicManager) Len() int {
	return len(m.musics)
}

func (m *MusicManager) Get(index int) (music *MusicEntry, err error) {
	if index < 0 || index >= len(m.musics) {
		return nil, errors.New("Index out of range.")
	}
	return &m.musics[index], nil
}

func (m *MusicManager) Find(name string) (index int, music *MusicEntry) {
	if len(m.musics) == 0 {
		return -1, nil
	}

	for i, m := range m.musics {
		if m.Name == name {
			return i, &m
		}
	}

	return -1, nil
}


func (m *MusicManager) Add(music *MusicEntry) {
	m.musics = append(m.musics, *music)
}

func (m *MusicManager) Remove(index int) (music *MusicEntry, err error) {
	if index < 0 || index >= len(m.musics) {
		return nil, errors.New("Index out of range.")
	}

	removedMusic := &m.musics[index]

	m.musics = append(m.musics[:index], m.musics[index + 1:]...)

	return removedMusic, nil
}

func (m *MusicManager) RemoveByName(name string) (music *MusicEntry, err error) {
	if name == "" {
		return nil, errors.New("empty parameter.")
	}

	index, _ := m.Find(name)

	if index == -1 {
		return nil, errors.New(fmt.Sprintf("Cann't find %s", name))
	}

	mm, _ := m.Remove(index)

	return mm, nil
}